package com.base.interception;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.base.controller.login.LoginController;
import com.base.model.LoginModel;
import com.base.model.authority.T_User;
import com.base.model.authority.T_UserRoles;
import com.base.model.log.T_Loginlog;
import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;

public class LoginInterceptor implements Interceptor {

	public void intercept(ActionInvocation ai) {
		HttpServletRequest request = ai.getController().getRequest();
		HttpServletResponse response = ai.getController().getResponse();
        String requrl = request.getServletPath();

        if (requrl.startsWith("/Msg") || requrl.startsWith("/Api") || requrl.startsWith("/Mobile")) {//不拦截微信消息和API、移动端
            ai.invoke();
            return;
        }
		if (null == ai.getController().getSessionAttr("loginModel")) {
			try {
				// 读取COOKIES判断是否其它应用已登录
				Cookie[] cookies = request.getCookies();
				Cookie cookie = null;
				if (cookies != null) {
					for (int i = 0; i < cookies.length; i++) {
						if ("oa_sessionId".equals(cookies[i].getName())) {
							cookie = cookies[i];
							break;
						}
					}
				}
				if (cookie != null) {
					T_Loginlog xtDljl = T_Loginlog.dao.findById(cookie.getValue());
					T_User user = T_User.dao.findById(xtDljl.getInt("u_id"));
					LoginModel loginModel = new LoginModel();
					loginModel.setUserId(user.getInt("id"));
					loginModel.setDlId(user.getStr("dlid"));
					loginModel.setUserName(user.getStr("name"));
					loginModel.setSessionId(xtDljl.getStr("sessionId"));
					if (null != user.get("d_id")) {
						loginModel.setDepartmentId(user.getInt("d_id"));
						loginModel.setDepsname(user.getDept().getStr("sname"));
					}
					loginModel.setLo(user.getStr("lo"));

					List<T_UserRoles> roles = user.getRoles();
					if (null == roles || 0 == roles.size()) {
						loginModel.setLimit("");
					} else {
						List<String> rlimits = new ArrayList<String>();
						for (T_UserRoles userRoles : roles) {
							if (null != userRoles.getRole().getStr("xtlimit")) {
								rlimits.add(userRoles.getRole().getStr("xtlimit").trim());
							}
						}
						if (0 == rlimits.size()) {
							loginModel.setLimit("");
						} else {
							StringBuffer buffer = new StringBuffer("");
							for (String string : rlimits) {
								String[] strings = string.split(",");
								for (int i = 0; i < strings.length; i++) {
									if (buffer.substring(0).indexOf(strings[i] + ",") == -1) {
										buffer.append(strings[i] + ",");
									}
								}
							}
							loginModel.setLimit(buffer.substring(0));
						}
					}
					request.getSession().setAttribute("loginModel", loginModel);
					LoginController.userMap.put(loginModel.getDlId(), request.getSession());
					/**
					 * 新增
					 */
					ai.getController().redirect(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/Main");
				} else {
					request.setCharacterEncoding("utf-8");
					response.setContentType("text/html;charset=UTF-8");
					response.getWriter().write(
							"<script language='JavaScript' type='text/javascript'" + " charset='utf-8'>alert('用户未登录或者登录超时，请重新登录！');\n " + " top.location.href='" + request.getContextPath()
									+ "/Login/index';</script>");
					response.getWriter().flush();
					response.getWriter().close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return;
		}
		ai.invoke();
	}

}
